// 引入请求工具
const { get, post } = require('../../utils/request');

Page({
  data: {
    userInfo: {},
    genderText: '未知',
    region: '未知',
    lastLoginTime: ''
  },
  
  onLoad() {
    this.getUserInfo();
  },
  
  onShow() {
    // 每次显示页面时刷新用户信息
    this.getUserInfo();
  },
  
  // 获取用户信息
  getUserInfo() {
    const app = getApp();
    if (!app.globalData.token) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    wx.showLoading({
      title: '加载中...',
    });
    
    get('/api/user/getUserInfo').then(res => {
      wx.hideLoading();
      if (res.code === 200 && res.data) {
        // 格式化性别
        let genderText = '未知';
        if (res.data.gender === 1) {
          genderText = '男';
        } else if (res.data.gender === 2) {
          genderText = '女';
        }
        
        // 格式化地区
        const country = res.data.country || '';
        const province = res.data.province || '';
        const city = res.data.city || '';
        const region = [country, province, city].filter(Boolean).join(' ') || '未知';
        
        // 格式化最后登录时间
        let lastLoginTime = '未知';
        if (res.data.lastLoginTime) {
          const loginTime = new Date(res.data.lastLoginTime);
          lastLoginTime = `${loginTime.getFullYear()}-${loginTime.getMonth() + 1}-${loginTime.getDate()} ${loginTime.getHours()}:${loginTime.getMinutes()}:${loginTime.getSeconds()}`;
        }
        
        this.setData({
          userInfo: res.data,
          genderText,
          region,
          lastLoginTime
        });
        
        // 更新全局用户信息
        app.globalData.userInfo = res.data;
      } else {
        // 用户信息获取失败，可能是token过期，跳转到登录页
        wx.redirectTo({
          url: '/pages/login/login'
        });
      }
    }).catch(() => {
      wx.hideLoading();
      wx.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      });
    });
  },
  
  // 绑定手机号
  bindPhone() {
    wx.showModal({
      title: '绑定手机号',
      content: '确定要绑定手机号码吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/login/login?bind=1'
          });
        }
      }
    });
  },
  
  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除登录信息
          const app = getApp();
          app.globalData.token = '';
          app.globalData.userInfo = null;
          wx.removeStorageSync('token');
          
          // 跳转到登录页
          wx.redirectTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
}) 